import sys
import os
import winreg
from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QMenu, QAction, QSystemTrayIcon,
    QTimeEdit, QVBoxLayout, QHBoxLayout, QDialog, QDialogButtonBox, QCheckBox
)
from PyQt5.QtGui import QIcon, QFont, QPainter, QLinearGradient, QColor, QPixmap
from PyQt5.QtCore import Qt, QTimer, QTime


def get_icon_from_base64(base64_data: bytes) -> QIcon:
    # 改为使用当前目录的 icon.ico
    return QIcon("./icon.ico")


class SettingsDialog(QDialog):
    """设置对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("工作时间设置")
        self.setFixedSize(300, 260)
        self.setWindowFlags(Qt.Dialog | Qt.WindowCloseButtonHint)

        layout = QVBoxLayout(self)

        # 上班时间
        time_layout = QHBoxLayout()
        time_label = QLabel("上班时间：")
        self.time_edit = QTimeEdit()
        self.time_edit.setDisplayFormat("HH:mm")
        time_layout.addWidget(time_label)
        time_layout.addWidget(self.time_edit)
        layout.addLayout(time_layout)

        # 午休开始
        rest_start_layout = QHBoxLayout()
        rest_start_label = QLabel("午休开始：")
        self.rest_start_edit = QTimeEdit()
        self.rest_start_edit.setDisplayFormat("HH:mm")
        rest_start_layout.addWidget(rest_start_label)
        rest_start_layout.addWidget(self.rest_start_edit)
        layout.addLayout(rest_start_layout)

        # 午休结束
        rest_end_layout = QHBoxLayout()
        rest_end_label = QLabel("午休结束：")
        self.rest_end_edit = QTimeEdit()
        self.rest_end_edit.setDisplayFormat("HH:mm")
        rest_end_layout.addWidget(rest_end_label)
        rest_end_layout.addWidget(self.rest_end_edit)
        layout.addLayout(rest_end_layout)

        # 午休计入开关
        self.include_rest_checkbox = QCheckBox("午休时间计入工作时长")
        layout.addWidget(self.include_rest_checkbox)

        # 按钮
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addSpacing(10)
        layout.addWidget(buttons)


class TimeCalculator(QWidget):
    """主界面"""
    def __init__(self):
        super().__init__()
        # 默认值
        self.work_start = QTime(9, 0)
        self.work_duration = 8.0
        self.rest_start_time = QTime(12, 0)
        self.rest_end_time = QTime(13, 0)
        self.include_rest = False  # 默认午休计入

        self.initUI()
        self.initTray()

        self.updateOffTime()
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateStatus)
        self.timer.start(1000)

    def initUI(self):
        self.setWindowTitle("搬砖助手")
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SubWindow)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setFixedSize(280, 200)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 15, 20, 15)
        layout.setSpacing(10)

        # 标题栏
        title_layout = QHBoxLayout()
        title_label = QLabel("⏰ 搬砖助手")
        title_label.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        title_label.setStyleSheet("color: rgba(255,255,255,0.95);")
        title_layout.addWidget(title_label)
        title_layout.addStretch()

        close_btn = QLabel("✕")
        close_btn.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        close_btn.setStyleSheet("color: rgba(255,255,255,0.7); padding: 4px 8px;")
        close_btn.setCursor(Qt.PointingHandCursor)
        close_btn.mousePressEvent = lambda e: self.hide()
        title_layout.addWidget(close_btn)
        layout.addLayout(title_layout)

        # 上班时间
        self.start_label = QLabel(f"🕘 上班时间：{self.work_start.toString('HH:mm')}")
        self.start_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        self.start_label.setAlignment(Qt.AlignCenter)
        self.start_label.setStyleSheet("""
            QLabel {
                color: rgba(255,255,255,0.9);
                padding: 6px;
                border-radius: 8px;
                background: rgba(255,255,255,0.03);
            }
        """)
        layout.addWidget(self.start_label)

        # 下班时间
        self.off_label = QLabel("⏰ 下班时间：--:--")
        self.off_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        self.off_label.setAlignment(Qt.AlignCenter)
        self.off_label.setStyleSheet("""
            QLabel {
                color: rgba(255,255,255,0.9);
                padding: 6px;
                border-radius: 8px;
                background: rgba(255,255,255,0.03);
            }
        """)
        layout.addWidget(self.off_label)

        # 状态 & 倒计时
        status_layout = QHBoxLayout()

        # 左侧：工作状态
        self.status_label = QLabel("💼 搬砖中")
        self.status_label.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        self.status_label.setStyleSheet("color: rgba(255,255,255,0.95);")
        status_layout.addWidget(self.status_label)

        # 中间自动填充空白（左右分开关键）
        status_layout.addStretch()

        # 右侧：倒计时
        self.countdown_label = QLabel("距离下班：--")
        self.countdown_label.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        self.countdown_label.setStyleSheet("color: rgba(255,255,255,0.95);")
        status_layout.addWidget(self.countdown_label)

        layout.addLayout(status_layout)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_settings_menu)
        self.dragging = False

    def show_settings_menu(self, pos):
        menu = QMenu(self)
        menu.setStyleSheet("""
            QMenu {
                background-color: rgba(40,40,45,220);
                color: rgba(255,255,255,0.95);
                border-radius: 8px;
                padding: 6px;
            }
            QMenu::item {
                padding: 6px 18px;
                border-radius: 6px;
            }
            QMenu::item:selected {
                background: rgba(255,255,255,0.06);
            }
        """)
        settings_action = QAction("⚙️ 设置工作时间", self)
        settings_action.triggered.connect(self.show_settings_dialog)
        menu.addAction(settings_action)
        menu.exec_(self.mapToGlobal(pos))

    def show_settings_dialog(self):
        dialog = SettingsDialog(self)
        dialog.time_edit.setTime(self.work_start)
        dialog.rest_start_edit.setTime(self.rest_start_time)
        dialog.rest_end_edit.setTime(self.rest_end_time)
        dialog.include_rest_checkbox.setChecked(self.include_rest)

        if dialog.exec_() == QDialog.Accepted:
            self.work_start = dialog.time_edit.time()
            self.rest_start_time = dialog.rest_start_edit.time()
            self.rest_end_time = dialog.rest_end_edit.time()
            self.include_rest = dialog.include_rest_checkbox.isChecked()
            self.updateOffTime()
            self.start_label.setText(f"🕘 上班时间：{self.work_start.toString('HH:mm')}")

    def initTray(self):
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(get_icon_from_base64(b""))
        tray_menu = QMenu()
        tray_menu.setStyleSheet("""
            QMenu {
                background-color: rgba(40,40,45,220);
                color: rgba(255,255,255,0.95);
                border-radius: 8px;
                padding: 6px;
            }
        """)
        tray_menu.addAction("显示窗口", self.show)
        tray_menu.addAction("隐藏窗口", self.hide)
        tray_menu.addAction("设置工作时间", self.show_settings_dialog)

        self.autostart_action = QAction("开机自启", self)
        self.autostart_action.setCheckable(True)
        self.autostart_action.setChecked(self.is_auto_start())
        self.autostart_action.toggled.connect(self.toggle_auto_start_from_action)
        tray_menu.addAction(self.autostart_action)

        tray_menu.addSeparator()
        tray_menu.addAction("退出程序", QApplication.quit)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.activated.connect(self.tray_icon_activated)
        self.tray_icon.show()

    def tray_icon_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.setVisible(not self.isVisible())

    def is_auto_start(self):
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                 r"Software\\Microsoft\\Windows\\CurrentVersion\\Run")
            winreg.QueryValueEx(key, "WorkTimeHelper")
            winreg.CloseKey(key)
            return True
        except Exception:
            return False

    def toggle_auto_start_from_action(self, checked):
        success = self.set_auto_start(checked)
        if not success:
            self.autostart_action.blockSignals(True)
            self.autostart_action.setChecked(not checked)
            self.autostart_action.blockSignals(False)

    def set_auto_start(self, enable: bool) -> bool:
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                 r"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
                                 0, winreg.KEY_SET_VALUE)
            if enable:
                exe_path = os.path.abspath(sys.argv[0])
                winreg.SetValueEx(key, "WorkTimeHelper", 0, winreg.REG_SZ, f'"{exe_path}"')
            else:
                winreg.DeleteValue(key, "WorkTimeHelper")
            winreg.CloseKey(key)
            return True
        except Exception as e:
            print("设置开机自启失败：", e)
            return False

    def updateOffTime(self):
        rest_seconds = self.rest_start_time.secsTo(self.rest_end_time)
        total_seconds = int(self.work_duration * 3600)
        if not self.include_rest:
            total_seconds += rest_seconds
        off_time = self.work_start.addSecs(total_seconds)
        self.off_label.setText(f"⏰ 下班时间：{off_time.toString('HH:mm')}")
        self.updateStatus()

    def updateStatus(self):
        now = QTime.currentTime()
        start = self.work_start
        rest_start = self.rest_start_time
        rest_end = self.rest_end_time
        rest_seconds = rest_start.secsTo(rest_end)
        total_seconds = int(self.work_duration * 3600)
        if not self.include_rest:
            total_seconds += rest_seconds
        off = start.addSecs(total_seconds)

        if now < start:
            status_text = "💤 未上班"
            status_color = "rgba(116,185,255,1)"
            countdown_text = ""
        elif rest_start <= now < rest_end:
            status_text = "🍜 午休中"
            status_color = "rgba(253,203,110,1)"
            countdown_text = f"距离午休结束：{self.format_countdown(now.secsTo(rest_end))}"
        elif start <= now < off:
            status_text = "💼 搬砖中"
            status_color = "rgba(0,184,148,1)"
            countdown_text = f"距离下班：{self.format_countdown(now.secsTo(off))}"
        else:
            status_text = "🎉 下班啦！"
            status_color = "rgba(255,118,117,1)"
            countdown_text = ""

        self.status_label.setText(status_text)
        self.status_label.setStyleSheet(f"color: {status_color}; font-weight: bold;")
        self.countdown_label.setText(countdown_text)
        self.countdown_label.setStyleSheet(f"color: {status_color}; font-weight: bold;")

    def format_countdown(self, seconds):
        """格式化倒计时为 时分秒"""
        if seconds <= 0:
            return "已结束"

        h = seconds // 3600
        m = (seconds % 3600) // 60
        s = seconds % 60

        if h > 0:
            return f"{h}:{m}:{s}"
        elif m > 0:
            return f"{m}:{s}"
        else:
            return f"{s}"

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        gradient = QLinearGradient(0, 0, 0, self.height())
        gradient.setColorAt(0, QColor(255, 255, 255, 18))
        gradient.setColorAt(1, QColor(20, 28, 40, 160))
        painter.setBrush(gradient)
        painter.setPen(QColor(255, 255, 255, 30))
        painter.drawRoundedRect(self.rect(), 14, 14)

    def mousePressEvent(self, e):
        if e.button() == Qt.LeftButton:
            self.dragging = True
            self.drag_position = e.globalPos() - self.frameGeometry().topLeft()

    def mouseMoveEvent(self, e):
        if self.dragging and e.buttons() == Qt.LeftButton:
            self.move(e.globalPos() - self.drag_position)

    def mouseReleaseEvent(self, e):
        if e.button() == Qt.LeftButton:
            self.dragging = False


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    app.setStyle("Fusion")
    tool = TimeCalculator()
    tool.show()
    sys.exit(app.exec_())
